<template>
  监听开关：<input type="checkbox" v-model="isListen" @change="toggle" />
  <div class="speech-container">
    <div
      class="label-item"
      :class="{ active: item === current }"
      v-for="item in labels"
      :key="item"
    >
      {{ item }}
    </div>
  </div>
</template>

<script>
import { reactive, toRefs } from "vue";
import * as speechCommands from "@tensorflow-models/speech-commands";

const MODEL_PATH = "http://127.0.0.1:8080/speech";

export default {
  setup: async function () {
    const state = reactive({
      labels: [],
      isListen: false,
      current: "",
    });

    const recognizer = speechCommands.create(
      "BROWSER_FFT",
      null,
      MODEL_PATH + "/model.json",
      MODEL_PATH + "/metadata.json"
    );

    await recognizer.ensureModelLoaded();

    const labels = recognizer.wordLabels();
    state.labels = labels;

    //切换
    async function toggle() {
      if (state.isListen) {
        await recognizer.listen(
          (result) => {
            const { scores } = result;
            const maxValue = Math.max(...scores);
            const index = scores.indexOf(maxValue) - 2;
            const current = labels[index];
            state.current = current;
            console.log(current);
          },
          {
            includeSpectrogram: true,
            probabilityThreshold: 0.9,
          }
        );
      } else {
        recognizer.stopListening();
      }
    }

    return {
      ...toRefs(state),
      toggle,
    };
  },
};
</script>

<style lang="scss" scoped>
.speech-container {
  display: flex;
  flex-wrap: wrap;

  .label-item {
    width: 100px;
    height: 100px;
    line-height: 100px;
    margin-right: 10px;
    background: #000000;
    color: #ffffff;
    margin-bottom: 10px;
    text-align: center;
    &.active {
      background: orange;
    }
  }
}
</style>